package com.hmall.gateway.filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpStatus;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter,Ordered {


    private final AuthProperties authProperties;


    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final JwtTool jwtTool;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否不需要拦截
        if(isExclude(request.getPath().toString()))
        {
            //匹配AuthProperties类读取文件里不需要拦截的路径则无需拦截
            return chain.filter(exchange);
        }
        //3.获取请求头中的token
        String token=null;
        List<String> headers = request.getHeaders().get("authorization");
        if (CollUtils.isNotEmpty(headers)) {
            token = headers.get(0);
        }

        //4.校验并解析token
        Long userId=null;
        try {
            userId=jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            // 拦截，设置响应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(HttpStatus.SC_UNAUTHORIZED);
            return response.setComplete();

        }

        //5.给下游微服务传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();

        //6.最后放行,把新上下文exchange给下游
        return chain.filter(newExchange);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }


        return false;
    }

    @Override
    public int getOrder() {

        return 0;
    }
}
